<template>
  <div class="cart">
    <CommonHeader title="购物车"></CommonHeader>
    <!-- 购物车列表 -->
    <div class="cart_list" v-if="cartList.length">
      <SwipeCell :title="item.goodsname" :description="item.desc" :price="item.price" :quantity="item.num"
        v-for="item in cartList" :key="item.id">
        <template #left-checked>
          <div class="roundedcorner" :class="{ active: item.status }" @click="isSingleCheckedSwitch(item)"></div>
        </template>
        <template #left-image>
          <img :src="item.img" alt="" />
        </template>
        <template #quantity>
          <Stepper :num="item.num" :max="20" @add="addnum(item)" @minus="minusnum(item)" />
        </template>
        <!-- 右侧删除按钮 -->
        <template #right>
          <div class="cart_list_item_info_num_delete" @click="deleteCart(item.id)">
            删除
          </div>
        </template>
      </SwipeCell>
    </div>
    <div class="cart_footer_no_goods" v-else>
      <img src="static/img/kongcart.jpeg" alt="" />
      <p>购物车空空如也</p>
      <button @click="toShop">去逛逛吧~</button>
    </div>

    <!-- 底部Submit Order -->
    <div class="cart_footer" :class="{ active: cartList.length }">
      <!-- 勾选 -->
      <div class="cart_footer_check" :class="{ active: isAllChecked }" @click="isAllCheckedSwitch"></div>
      <div class="footer_right">
        <div class="cart_footer_total">
          <p>
            合计:
            <span class="cart_footer_total_price">{{ totalPriceA > 0 ? '¥' + totalPriceA : '' }}</span>
          </p>
        </div>
        <div class="cart_footer_submit" @click="toOrderConfirmation">
          <button>提交订单</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import CommonHeader from '@/components/common/publicHeader/index.vue';

import SwipeCell from '@/components/common/swipeCell/index.vue';
import { getCartListAPI, addCartNumAPI, minusCartNumAPI } from '@/api/cart';
import showDialog from '@/utils/dialog';
import { deleteCartAPI } from '@/api/cart';
import Message from '@/utils/message';
import Stepper from '@/components/common/Stepper/index.vue';

export default {
  components: {
    CommonHeader,
    SwipeCell,
    Stepper,
  },
  data() {
    return {
      cartList: [],
      // 是否全选
      isAllChecked: false,
    };
  },
  mounted() {
    this.getCartList();
  },
  methods: {
    toShop() {
      this.$router.push({
        path: '/home',
      });
    },
    // 去订单确认页
    toOrderConfirmation() {
      // 检查是否有勾选的商品
      if (!this.totalPriceA) {
        Message({
          message: '请选择商品',
          type: 'info',
        });
        return;
      }
      this.cartList = this.cartList.filter(item => item.status);
      // 保存本地存储
      localStorage.setItem('cartList', JSON.stringify(this.cartList));
      // 作者信息保存到本地存储
      localStorage.setItem(
        'authorInfo',
        JSON.stringify({
          username: '作者',
          userphone: '13800000000',
        })
      );
      this.$router.push({ name: 'orderConfirmation' });
    },

    // 获取购物车列表
    async getCartList() {
      const { uid } = JSON.parse(localStorage.getItem('userinfo'));
      const res = await getCartListAPI({
        uid,
      });
      const { list } = res;

      // 拼接图片路径
      // 如果list为空
      if (!list) {
        this.cartList = [];
        return;
      }
      this.cartList = list.map(item => {
        item.img = 'http://43.138.15.137:4000/' + item.img;
        return item;
      });
      // 检查是否所有商品都被选中
      const allChecked = this.cartList.every(cartItem => cartItem.status);
      // 更新全选状态
      this.isAllChecked = allChecked;
    },
    // 购物车数量添加请求
    async addnum(item) {
      await addCartNumAPI({
        id: item.id,
        type: 2,
      });
      item.num++;
    },
    async minusnum(item) {
      await minusCartNumAPI({
        id: item.id,
        type: 1,
      });
      item.num--;
    },
    // 全选
    isAllCheckedSwitch() {
      // 切换全选状态
      this.isAllChecked = !this.isAllChecked;
      // 更新所有商品的选中状态
      this.cartList.forEach(item => {
        item.status = this.isAllChecked;
      });
    },
    // 单选
    isSingleCheckedSwitch(item) {
      // 切换单个商品的选中状态
      item.status = !item.status;
      // 检查是否所有商品都被选中
      const allChecked = this.cartList.every(cartItem => cartItem.status);
      // 更新全选状态
      this.isAllChecked = allChecked;
    },
    // 删除
    async deleteCart(id) {
      showDialog({
        title: '删除商品',
        content: '确定删除该商品吗？',
        onConfirm: async () => {
          const res = await deleteCartAPI({
            id,
          });
          const { code, msg } = res;
          if (code === 200) {
            Message.success(msg);
            this.getCartList();
          } else {
            Message.error(msg);
          }
        },
      });
    },
  },
  computed: {
    // 计算合计
    totalPriceA() {
      let total = 0;
      this.cartList.forEach(item => {
        if (item.status) {
          total += item.price * item.num;
        }
      });
      return total;
    },
  },
};
</script>

<style lang="scss" scoped>
.cart {
  height: 100vh;
  background-color: #f5f5f5;
  position: relative;

  .roundedcorner {
    width: 15px;
    height: 15px;
    border-radius: 50%;
    border: 1px solid #ccc;
    position: relative;
    transition: all 0.3s ease-in-out;
    margin-right: 10px;

    &.active {
      background-color: #0076ff;
      border: 0;

      &::before {
        content: '';
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -60%) rotate(45deg);
        width: 4px;
        height: 8px;
        border-right: 1px solid #fff;
        border-bottom: 1px solid #fff;
      }
    }
  }

  .cart_list {
    height: 100%;
    display: flex;
    flex-direction: column;

    .cart_list_item {
      height: 100px;
      background-color: #fff;
      margin-bottom: 10px;
      display: flex;
      align-items: center;
      padding: 0 10px;
      gap: 10px;

      .cart_list_item_img {
        width: 90px;
        height: 80px;
        border-radius: 10px;
        overflow: hidden;

        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
      }

      p {
        margin-bottom: 5px;
      }

      .cart_list_item_info {
        flex: 1;
        height: 100px;
        padding: 10px;
        font-size: 14px;
        position: relative;
        color: #999;

        .cart_list_item_info_name {
          font-size: 16px;
          font-weight: 600;
        }

        .cart_list_item_info_desc {
          font-size: 14px;
          color: #999;
        }
      }
    }
  }

  .cart_footer {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 50px;
    opacity: 0;
    background-color: #fff;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10px;
    transition: all 0.3s ease-in-out;

    .cart_footer_check {
      width: 20px;
      height: 20px;
      border: 1px solid #ccc;
      border-radius: 50%;
      position: relative;

      &.active {
        background-color: #0076ff;
        border: 0;

        &::before {
          content: '';
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -60%) rotate(45deg);
          width: 4px;
          height: 8px;
          border-right: 1px solid #fff;
          border-bottom: 1px solid #fff;
        }
      }
    }

    .footer_right {
      width: 65%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 14px;

      .cart_footer_total {
        p {
          margin-left: 25px;

          font-size: 16px;
          display: flex;
          align-items: center;

          .cart_footer_total_price {
            font-size: 14px;
            color: #ff0000;
            font-weight: 600;
          }
        }
      }

      .cart_footer_submit {
        width: 120px;
        height: 40px;
        background-color: #ff0000;
        color: #fff;
        border-radius: 30px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 14px;
        margin-right: -10px;

        button {
          width: 100%;
          height: 100%;
          background-color: transparent;
          color: #fff;
        }
      }
    }

    &.active {
      bottom: 50px;
      opacity: 1;
    }
  }

  .cart_footer_no_goods {
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 80px 0;

    img {
      width: 100px;
      height: 100px;
    }

    p {
      margin: 10px 0;
      font-size: 16px;
    }

    button {
      width: 110px;
      height: 40px;
      background-color: #ff0200;
      color: #fff;
      border-radius: 2px;
    }
  }
}
</style>
